package com.kadron.users;

import java.util.List;

import javax.persistence.EntityManager;

import com.kadron.dao.KUserDAO;
import com.kadron.datamodel.KDataProvider;
import com.kadron.datamodel.KModel;
import com.kadron.datamodel.KModelCreator;
import com.kadron.entity.User;

public class KUserModelDataProvider implements KDataProvider {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1794019776258079877L;

	private KUserModelCreator creator;
	private KUserDAO userDAO;
	
	public KUserModelDataProvider(KUserModelCreator creator, KUserDAO userDAO) {
		super();
		this.creator = creator;
		this.userDAO = userDAO;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Long> getItemsByRange(Integer integer, int numberOfRows,
			Object object, boolean b) {
		EntityManager em = userDAO.getEntityManager();
		return em.createQuery("SELECT a.id FROM User a ").setFirstResult(integer).setMaxResults(numberOfRows).getResultList();
	}

	@Override
	public KModel getItemById(Long id, KModelCreator creator) {
		return creator.create(id);
	}

	@Override
	public int getRowCount() {
		EntityManager em = userDAO.getEntityManager();
		Long count = (Long) em.createQuery("SELECT COUNT(a.id) FROM User a ").getSingleResult();
		return (count == null) ? 0 : count.intValue() ;
	}

	@Override
	public boolean hasItemWithId(Long id) {
		return userDAO.exists(id, User.class);
	}

	@Override
	public KUserModelCreator getCreator() {
		return creator;
	}

}
